from django.core.files.storage import Storage
from django.utils.deconstruct import deconstructible
from fdfs_client.client import Fdfs_client

from constants.constant import fdfs_ip
from meiduo_mall import settings

@deconstructible
class FastDFSStorage(Storage):

    def __init__(self, conf_path=None, ip=None):
        if conf_path is None:
            conf_path = settings.FDFS_CLIENT_CONF
        self.conf_path = conf_path

        if ip is None:
            ip = settings.FDFS_URL
        self.ip = ip
    def _open(self, name, mode='rb'):
        pass

    def _save(self, name, content, max_length=None):
        client = Fdfs_client('utils/fastdfs/client.conf')
        file_data = content.read()
        result = client.upload_by_buffer(file_data)
        if result.get('Status') == 'Upload successed.':
            return result.get('Remote file_id')
        else:
            raise Exception('上传失败')

    def exists(self, name):
        return False

    def url(self, name):
        return fdfs_ip + name